/*
 * @Author       : 吴豪
 * @Date         : 2021-12-4 15:56:22
 * @FilePath     : \book-manage-front\src\pages\bookManage\booksComponents\CreateBook.tsx
 * @Description  : 新增图书模态框
 */

import type { ProFormInstance } from '@ant-design/pro-form';
import ProForm, { ProFormText, ProFormSelect, ProFormTextArea } from '@ant-design/pro-form';
import React from 'react';
import { message, Modal } from 'antd';
import { useRef, useState } from 'react';
import { checkISBNExist, getBookTypeList, saveBookInfo } from '@/services/books';

type LayoutType = Parameters<typeof ProForm>[0]['layout'];

/**
 * 将父级传来的数据解构，并执行新增操作
 * @param props
 * @returns
 */
const CreateBook = (props: { isModalVisible?: any; isShowModal?: any; actionRef?: any }) => {
  const { isModalVisible } = props;
  const { isShowModal } = props;
  const { actionRef } = props;

  const [formLayoutType] = useState<LayoutType>('horizontal');
  const [but, setBut] = useState<boolean>(false);
  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 16 },
  };

  const formRef = useRef<
    ProFormInstance<{
      aid: number;
      name: string;
      typeAid: number;
      isbn: string;
      quantity: number;
      remarks: string;
    }>
  >();

  /**
   * 添加图书
   */
  const handleOk = async () => {
    const books = await formRef.current?.validateFields();
    const prama = {
      aid: -1,
      name: books?.name || '',
      typeAid: books?.typeAid || -1,
      isbn: books?.isbn || '',
      quantity: books?.quantity || -1,
      remarks: books?.remarks || '',
    };
    const response = await saveBookInfo(prama);
    if (response) {
      message.success('添加成功！');
      isShowModal(false);
      actionRef.current.reload();
    } else {
      message.error('添加失败！');
    }
  };

  return (
    <Modal
      destroyOnClose
      title="新增图书"
      width="649px"
      visible={isModalVisible}
      onOk={handleOk}
      okButtonProps={{ disabled: but }}
      onCancel={() => {
        if (but) {
          setBut(false);
        }
        isShowModal();
      }}
    >
      <ProForm
        formRef={formRef}
        submitter={{
          submitButtonProps: {
            style: {
              display: 'none',
            },
          },
          resetButtonProps: {
            style: {
              display: 'none',
            },
          },
        }}
        {...layout}
        layout={formLayoutType}
        params={{}}
      >
        <ProFormText
          name="name"
          label="名称"
          placeholder="请输入"
          rules={[
            {
              required: true,
            },
          ]}
        />
        <ProFormSelect
          name="typeAid"
          label="类型"
          placeholder="请输入"
          rules={[
            {
              required: true,
              message: '请选择类型',
            },
          ]}
          //渲染图书类型下拉选择框
          request={async () => {
            const data = await getBookTypeList();
            return data.map((item) => {
              return {
                label: item.name,
                value: item.aid,
              };
            });
          }}
        />
        <ProFormText
          name="isbn"
          label="ISBN号"
          placeholder="请输入"
          fieldProps={{
            //输入框失焦时对ISBN号进行唯一性校验
            onBlur: async (event) => {
              const isbn = event.target.value;
              if (isbn) {
                const params = {
                  aid: -1,
                  isbn,
                };
                const response = await checkISBNExist(params);
                if (response.isExist) {
                  formRef.current?.setFieldsValue(response.bookInfo!);
                  message.error('该ISBN号已存在！');
                  setBut(true);
                } else {
                  setBut(false);
                }
              }
            },
          }}
          rules={[
            {
              required: true,
            },
            {
              pattern: new RegExp(/^978-[0-9]-[0-9]{4}-[0-9]{4}-[0-9|X]$/g),
              message: '请输入正确的ISBN号',
            },
          ]}
        />
        <ProFormText
          name="quantity"
          label="数量"
          placeholder="请输入"
          rules={[
            { required: true },
            { pattern: new RegExp(/^[1-9]\d*$/g), message: '请输入正整数' },
          ]}
        />
        <ProFormTextArea
          fieldProps={{ showCount: true, maxLength: 100 }}
          name="remarks"
          label="备注"
          placeholder="请输入"
        />
      </ProForm>
    </Modal>
  );
};
export default CreateBook;
